import React, { useMemo, useState } from 'react';
import Taro from '@tarojs/taro';
import { View, Text, Image } from '@tarojs/components';
import classNames from 'classnames';
import './index.less';
import store from '@/src/store';
import { formatPhoneNumber, isValidLocation } from '@/src/common/util/util';
import { AtNoticebar } from 'taro-ui';
export interface StoreInfoProps {
  /** 是否首页样式 */
  isHome: boolean;
  /** 额外的 className */
  className?: string;
  /** 行内样式 */
  style?: React.CSSProperties;
  /** 店铺信息 */
  storeInfo: any;
  /** 是否显示距离 */
  isShowDistance?: boolean;
}

const StoreInfo: React.FC<StoreInfoProps> = ({
  isHome,
  className,
  style,
  storeInfo,
  isShowDistance,
}) => {
  const rootClass = classNames('user-center-certify-merchant', className);
  const imgContainerClass = classNames(
    'user-center-business-img',
    `user-center-business-img-${isHome}`
  );

  /**
   * 米(m)格式化：<1000 m 时显示 m，>=1000 m 时显示 KM（一位小数）
   */
  const formatDistance = (meters: number): string => {
    if (meters < 1000) {
      return `${Math.round(meters)}m`;
    } else {
      return `${(meters / 1000).toFixed(1)}km`;
    }
  };

  // 打开地图导航
  const handleNavigate = () => {
    console.log('storeInfo=====', storeInfo);
    // 调用微信地图打开定位导航到此店
    if (!isValidLocation(storeInfo.latitude, storeInfo.longitude)) {
      Taro.showToast({
        title: '店铺位置信息异常',
        icon: 'none',
      });
      return;
    }
    Taro.openLocation({
      latitude: Number(storeInfo.latitude),
      longitude: Number(storeInfo.longitude),
      name: storeInfo.storeName,
      address: storeInfo.address,
      scale: 18,
    });
  };

  // 查看图片
  const gotoImageView = (index: number = 0) => {
    store.commonStore.setImages(storeInfo.imgList);
    if (index) {
      store.commonStore.setInitialIndex(index);
    }
    Taro.navigateTo({ url: '/subPagesAccount/imageView/index' });
  };

  const imgList = useMemo(() => {
    const { imgList } = storeInfo;
    if (imgList && imgList.length >= 3) {
      return imgList.slice(0, 3);
    } else {
      return imgList;
    }
  }, [storeInfo && storeInfo.imgList]);

  /** 根据 businessDays 和 businessHours 判断是否营业 */
  const isOpen = useMemo(() => {
    const { businessDays, businessHours } = storeInfo;
    // 1. 判断今天是否在营业日
    const today = new Date().getDay(); // 0–6，0=周日
    const daysSet = new Set(
      businessDays
        .split(',')
        .map((s: any) => parseInt(s, 10))
        .filter((n: any) => !isNaN(n))
    );
    if (!daysSet.has(today)) return false;

    // 2. 判断当前时间是否在营业时间段内
    const [start, end] = businessHours.split('-');
    if (!start || !end) return false;
    const now = new Date();
    const [sh, sm] = start.split(':').map((x) => parseInt(x, 10));
    const [eh, em] = end.split(':').map((x) => parseInt(x, 10));
    const startTime = new Date(now);
    startTime.setHours(sh, sm, 0, 0);
    const endTime = new Date(now);
    endTime.setHours(eh, em, 0, 0);
    return now >= startTime && now <= endTime;
  }, [storeInfo.businessDays, storeInfo.businessHours]);

  /**
   * 把 "0,1,2" 这种字符串格式转成我们要的周几显示
   */
  const formatBusinessDays = (daysStr: string): string => {
    if (!daysStr) return '';
    const dayMap: Record<number, string> = {
      1: '周一',
      2: '周二',
      3: '周三',
      4: '周四',
      5: '周五',
      6: '周六',
      0: '周日',
    };
    // 拆分、去重、映射：把 0 暂时映射到 7，方便后面排序把周日放最后
    const nums = Array.from(
      new Set(
        daysStr
          .split(',')
          .map((s) => parseInt(s, 10))
          .filter((n) => !isNaN(n))
          .map((n) => (n === 0 ? 7 : n))
      )
    )
      .sort((a, b) => a - b)
      .map((n) => (n === 7 ? 0 : n));

    // 全周
    if (nums.length === 7) {
      return '周一至周日';
    }
    // 周一至周五
    if (nums.length === 5 && nums[0] === 1 && nums[4] === 5) {
      return '周一至周五';
    }
    // 周一至周六
    if (nums.length === 6 && nums[0] === 1 && nums[5] === 6) {
      return '周一至周六';
    }
    // 其他：逐个列出，用顿号分隔
    return nums.map((d) => dayMap[d]).join('、');
  };
  return (
    <View className={rootClass} style={style}>
      <View className="user-center-shop">
        <Text
          className={classNames('user-center-status', {
            open: isOpen,
            closed: !isOpen,
          })}
        >
          {isOpen ? '营业中' : '休息中'}
        </Text>
        <View className="user-center-shop-name clamp1">
          {storeInfo.storeName.length > 20 ? (
            <AtNoticebar marquee>{storeInfo.storeName}</AtNoticebar>
          ) : (
            storeInfo.storeName.substring(0, 20)
          )}
        </View>
        {isShowDistance && (
          <View className="user-center-position">
            {formatDistance(storeInfo.distance)}
          </View>
        )}
      </View>

      <View className="user-center-business">
        <View className="user-center-business-left">
          <Text className="user-center-time">
            营业时间：{' '}
            {formatBusinessDays(storeInfo.businessDays) +
              ' ' +
              storeInfo.businessHours}
          </Text>
          <View className="user-center-time">地址：{storeInfo.address}</View>
        </View>
        <View className="user-center-business-right">
          <View className="user-center-mobile-wrap">
            <Image
              src="https://file.linkcook.cn/image/wineMiniProgram/home/mobile.png"
              className="user-center-mobile"
              onClick={() =>
                Taro.makePhoneCall({
                  phoneNumber: formatPhoneNumber(storeInfo.contactPhone),
                })
              }
            />
          </View>
          <View className="user-center-mobile-wrap" onClick={handleNavigate}>
            <Image
              src="https://file.linkcook.cn/image/wineMiniProgram/home/navigate.png"
              className="user-center-navigate"
            />
          </View>
        </View>
      </View>

      <View className={imgContainerClass}>
        {imgList &&
          imgList.slice(0, 3).map((item: any, index: number) => {
            return (
              <Image
                key={index}
                src={item}
                className="user-center-business-item"
                onClick={() => {
                  gotoImageView(index);
                }}
              />
            );
          })}
        {storeInfo.imgList && storeInfo.imgList.length > 3 && (
          <View className="home-subscript" onClick={() => gotoImageView()}>
            <Image
              src={
                'https://file.linkcook.cn/image/wineMiniProgram/home/numer_image.png'
              }
            />
            <Text>{storeInfo.imgList && storeInfo.imgList.length}</Text>
          </View>
        )}
        {/* 角标 */}
      </View>
    </View>
  );
};

export default StoreInfo;
